<template>
  <div class="page-user-chat">
    <van-nav-bar left-arrow @click-left="$router.back()" title="登录"></van-nav-bar>
    <van-cell-group>
      <ValidationObserver ref="loginFormRef">
      <ValidationProvider rules="required|phone" name="手机号" v-slot="{ errors }">
      <van-field
      v-model="loginForm.mobile"
      type="tel"
      placeholder="请输入手机号码"
      label="手机号"
      required
      clearable
      :error-message="errors[0]"
      />
      </ValidationProvider>
      <ValidationProvider rules="required" name="验证码" v-slot="{ errors }">
      <van-field
      v-model="loginForm.code"
      type="password"
      placeholder="请输入验证码"
      label="验证码"
      required
      clearable
      :error-message="errors[0]"
      >
      <van-button slot="button" size="small" type="primary">发送验证码</van-button>
      </van-field>
      </ValidationProvider>
      </ValidationObserver>
    </van-cell-group>
    <div class="login-btn">
      <van-button type="info" size="small" round block @click="login()" :loading="isLogin" loading-text="登录中...">登录</van-button>
    </div>
  </div>
</template>

<script>
import { apiUserLogin } from '@/api/user.js'
import { ValidationProvider, ValidationObserver } from 'vee-validate'
export default {
  name: 'user-login',
  data () {
    return {
      loginForm: {
        mobile: '13911111111',
        code: '246810'
      },
      isLogin: false
    }
  },
  components: {
    ValidationProvider,
    ValidationObserver
  },
  methods: {
    async login () {
      const rst = await this.$refs.loginFormRef.validate()
      if (!rst) {
        return false
      }
      this.isLogin = true
      try {
        const result = await apiUserLogin(this.loginForm)
        this.$store.commit('updateUser', result)
      } catch (err) {
        return this.$toast.fail('用户名或密码错误' + err)
      }
      this.isLogin = false
      this.$toast.success('登录成功')
      this.$router.push('/home')
    }
  }
}
</script>

<style scoped lang='less'>
.login-btn {
  margin: 40px;
}
</style>
